package ctn.web.home.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import ctn.service.dto.PFileDTO;
import ctn.util.CTNUserUtil;
import ctn.util.FileUtil;
import ctn.util.StringUtils;
import ctn.util.jmesa.DateUtils;

@Controller
public class UserPriFileController {
	@Autowired
	@Qualifier("filePro")
	private Properties filePro;

	@RequestMapping(value = "/main/filelist")
	public ModelAndView fileList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("file/filelist");
		File file = new File(getFileAbsoultPath(request));
		if(!file.exists()){
			file.mkdirs();
		}
		File[] fileArr = file.listFiles();
		List<PFileDTO> cfileList = new ArrayList<PFileDTO>();
		for (File cfile : fileArr) {
			PFileDTO pfile = new PFileDTO();
			pfile.setFileName(cfile.getName());
			String pfilepath = getChildPath(request) + "/" + cfile.getName();
			pfilepath = URLEncoder.encode(pfilepath, "utf-8");
			if (cfile.isDirectory()) {
				pfile.setFilePath(getFileAbsoultPath(request)+pfilepath);
				pfile.setFileUrl("/app/filelist?path=" + pfilepath);
				pfile.setFileTyp("F");
			} else {
				pfile.setFileUrl("/app/openFile?path=" + pfilepath);
				pfile.setFilePath(getFileAbsoultPath(request)+pfilepath);
				String fileExtStr = cfile.getName().substring(
						cfile.getName().lastIndexOf(".") + 1,
						cfile.getName().length());
				pfile.setFileTyp(fileExtStr);
			}

			cfileList.add(pfile);
		}
		mv.addObject("fileList", cfileList);
		mv.addObject("path",
				URLEncoder.encode(getFileAbsoultPath(request), "utf-8"));
		return mv;
	}

	@RequestMapping(value = "/main/openFile")
	public void openFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String path = getFileAbsoultPath(request);
		File file = new File(path);
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control", "max-age=0");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ new String(file.getName().getBytes(), "UTF-8"));
		BufferedOutputStream os = null;
		BufferedInputStream is = null;
		try {
			os = new BufferedOutputStream(response.getOutputStream());
			is = new BufferedInputStream(new FileInputStream(file));

			byte[] byteA;
			int read = 0;
			while (read != -1) {
				byteA = new byte[1024];
				read = is.read(byteA);
				if (read != -1) {
					os.write(byteA, 0, read);
				}
			}
			os.flush();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				try {
					os.close();
				} catch (Exception ex) {
				}
			}
		}

	}

	@RequestMapping(value = "/main/precreatef")
	public ModelAndView precreatef(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("file/createfile");
		PFileDTO dto = new PFileDTO();
		dto.setFilePath(request.getParameter("path"));
		dto.setFileTyp("F");
		mv.addObject("createFileDTO", dto);

		return mv;
	}

	@RequestMapping(value = "/main/creatf")
	public ModelAndView createf(HttpServletRequest request,
			HttpServletResponse response,
			@ModelAttribute("createFileDTO") PFileDTO createFileDTO,
			BindingResult errors) throws Exception {
		ModelAndView mv = new ModelAndView("file/createfile");

		File f = new File(createFileDTO.getFilePath() + "/"
				+ createFileDTO.getFileName());

		if (f.exists()) {
			errors.rejectValue("fileName", null, "文件夹名称重复。");
		}
		if (errors.hasErrors()) {
			mv.setViewName("file/createfile");
		} else {
			f.mkdir();
		}

		return mv;
	}

	@RequestMapping(value = "/main/preuploadf")
	public ModelAndView preuploadf(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("file/uploadfile");
		PFileDTO dto = new PFileDTO();
		dto.setFilePath(request.getParameter("path"));
		mv.addObject("uploadFileDTO", dto);

		return mv;
	}

	@RequestMapping(value = "/main/uploadf")
	public ModelAndView uploadf(HttpServletRequest request,
			HttpServletResponse response,
			@ModelAttribute("uploadFileDTO") PFileDTO uploadFileDTO,
			BindingResult errors) throws Exception {
		ModelAndView mv = new ModelAndView("file/uploadfile");

		if (uploadFileDTO.getUpFile() == null) {
			errors.rejectValue("upFile", null, "文件路径不能为空。");
		} else {
			CommonsMultipartFile uf = uploadFileDTO.getUpFile();
			File file = new File(uploadFileDTO.getFilePath() + "/"
					+ DateUtils.formatDateTime("yyyyMMdd", new Date()) + "_"
					+ uf.getOriginalFilename());
			int count = 1;
			while (file.exists()) {
				file = new File(uploadFileDTO.getFilePath() + "/"
						+ DateUtils.formatDateTime("yyyyMMdd", new Date())
						+ "_" + count + "_" + uf.getOriginalFilename());
				count++;
			}
			BufferedOutputStream os = null;
			BufferedInputStream is = null;
			try {
				os = new BufferedOutputStream(new FileOutputStream(file));
				is = new BufferedInputStream(uf.getInputStream());

				byte[] byteA;
				int read = 0;
				while (read != -1) {
					byteA = new byte[1024];
					read = is.read(byteA);
					if (read != -1) {
						os.write(byteA, 0, read);
					}
				}
				os.flush();
			} finally {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					try {
						os.close();
					} catch (Exception ex) {
					}
				}
			}
		}

		return mv;
	}

	@RequestMapping(value = "/main/delf")
	public ModelAndView delf(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("file/uploadfile");
		File f = new File(request.getParameter("path"));
		String parentPath = filePro.getProperty("personal.tmpfile.path");
		String userName = CTNUserUtil.getUser().getName();
		StringBuffer path = new StringBuffer();
		path.append(parentPath).append("/").append(userName);
		File tof = new File(path.toString() + "/" + f.getName());
		FileUtil.cutFolder(f, tof);
		return mv;
	}

	private String getFileAbsoultPath(HttpServletRequest request)
			throws Exception {
		String parentPath = filePro.getProperty("personal.file.path");
		String userName = CTNUserUtil.getUser().getName();
		StringBuffer path = new StringBuffer();
		path.append(parentPath).append("/").append(userName);

		path.append(getChildPath(request));
		return path.toString();
	}

	private String getChildPath(HttpServletRequest request) throws Exception {
		String childPath = request.getParameter("path");
		if (!StringUtils.isEmptyString(childPath)) {
			childPath = URLDecoder.decode(childPath, "utf-8");
		}
		return childPath == null ? "" : childPath;
	}
}
